﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

using LightLog.Model.Config;
using LightLog.IService;
using LightLog.Service;
using FreeSqlExtensions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using JwtHelper = LightLog.Service.JwtHelper;

namespace LightLog.Service
{
    public class LoginService:BaseService,ILoginService
    {
        private readonly IFreeSql _fsql;
        private readonly IHttpContextAccessor _accessor;
        private readonly JwtConfig _jwtConfig;


        public LoginService(IFreeSql fsql,IHttpContextAccessor accessor, JwtConfig jwtConfig)
        {
            _fsql = fsql;
            _accessor = accessor;
            _jwtConfig = jwtConfig;
        }

        public async Task<(string,long)> LoginAsync(string username, string pwd)
        {
            long adminid = 0;

            var pwdStr =Framework.Security.GetMd5Pwd(pwd);
            var admin = await _fsql.Select<Entity.User>()
                .Where(p =>  p.Pwd == pwdStr && p.UserName == username)
                .FirstAsync(p => new { p.ID });


            if (admin == null)
            {
                return ("用户名或密码错误!", 0);
            }

            return ("", admin.ID);
        }

        /// <summary>
        /// 获取token和刷新token
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public (string, string) GetAccessTokenAndRefreshToken(string userName, string userId)
        {
            var claims = new Claim[]
            {
                new Claim(ClaimName.UserId,userId),
            };

            var accessToken=  JwtHelper.CreateToken(claims, _jwtConfig);
            var refreshToken =  JwtHelper.GetRefreshToken(claims, _jwtConfig);

            return (accessToken, refreshToken);
        }

        /// <summary>
        /// 获取刷新token
        /// </summary>
        /// <returns></returns>
        public string RefreshToken()
        {
            var token = _accessor.HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];

            return  JwtHelper.RefreshAccessToken(token, _jwtConfig);
        }


    }
}
